package com.servlet.user;

import com.domain.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "registerServlet", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            // 将获取到的map集合封装到实体类中
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        // 调用service方法
        UserService service = new UserServiceImpl();
        User user1 = service.selectOne(user);
        // 设置响应编码
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        if(user1 != null ) {
            response.getWriter().write("{\"status\":2,\"message\":\"用户名已存在\"}");
        }else {
            if(service.save(user)) {
                response.getWriter().write("{\"status\":0,\"message\":\"ok\"}");
            }else {
                response.getWriter().write("{\"status\":1,\"message\":\"error\"}");
            }
        }
    }
}
